﻿using System;
using Microsoft.VisualStudio.TemplateWizard;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.IO;

namespace CodeCounsel.SharePoint.DevTools.ItemTypes
{
    public class SandboxedVisualWebPartWizard
        : IWizard
    {
        public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
        {
        }

        public void ProjectFinishedGenerating(EnvDTE.Project project)
        {
        }

        public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
        {
            if (projectItem != null &&
                String.Equals(Path.GetExtension(projectItem.Name), ".ascx", StringComparison.OrdinalIgnoreCase))
            {
                EnvDTE.Property property = projectItem.Properties.Item("CustomTool");
                property.Value = "SandboxedVisualWebPartGenerator";
            }
        }

        public void RunFinished()
        {
        }

        public void RunStarted(object automationObject, 
            Dictionary<string, string> replacementsDictionary, 
            WizardRunKind runKind, object[] customParams)
        {
            string ascxGeneratedName = replacementsDictionary["$ascx_generatedName$"];
            replacementsDictionary.Add("$ascx_generatedNameLC$", ascxGeneratedName.ToLower());
            if (replacementsDictionary.ContainsKey("$rootname$"))
            {
                replacementsDictionary.Add("$subnamespace$", MakeNameCompliant(replacementsDictionary["$rootname$"]));
            }
            if (replacementsDictionary.ContainsKey("$safeitemrootname$"))
            {
                string rootName = replacementsDictionary["$safeitemrootname$"];
                if (String.IsNullOrEmpty(rootName) == false)
                {
                    replacementsDictionary.Add(
                        "$safeitemrootnamelowercase$",
                        rootName.ToLower());
                }
            }
        }

        static string MakeNameCompliant(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return string.Empty;
            }
            if (char.IsDigit(name[0]))
            {
                name = "_" + name;
            }
            StringBuilder builder = new StringBuilder(name.Length);
            foreach (char ch in name)
            {
                if (IsValidCharForName(ch))
                {
                    builder.Append(ch);
                }
                else
                {
                    builder.Append('_');
                }
            }
            name = builder.ToString();
            return name;
        }
        static bool IsValidCharForName(char currentChar)
        {
            UnicodeCategory unicodeCategory = char.GetUnicodeCategory(currentChar);
            if (((((unicodeCategory != UnicodeCategory.UppercaseLetter) && (unicodeCategory != UnicodeCategory.LowercaseLetter)) && ((unicodeCategory != UnicodeCategory.OtherLetter) && (unicodeCategory != UnicodeCategory.ConnectorPunctuation))) && (((unicodeCategory != UnicodeCategory.ModifierLetter) && (unicodeCategory != UnicodeCategory.NonSpacingMark)) && ((unicodeCategory != UnicodeCategory.SpacingCombiningMark) && (unicodeCategory != UnicodeCategory.TitlecaseLetter)))) && (((unicodeCategory != UnicodeCategory.Format) && (unicodeCategory != UnicodeCategory.LetterNumber)) && ((unicodeCategory != UnicodeCategory.DecimalDigitNumber) && (currentChar != '.'))))
            {
                return (currentChar == '_');
            }
            return true;
        }

        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }
    }
}
